<template>
  <div class="audition201">
    <p>用虚拟列表思想处理：</p>
    <p>图示：</p>
    <img src="@images/xuniliebiao1.png" alt="" class="img">
    <p>加载10万条数据，展示：</p>
    <div class="container">
      <div class="msg msg-head">
        <span>编号</span>
        <span>品名</span>
        <span>单价(/kg)</span>
      </div>
      <div class="content" ref="content">
        <ul class="ul_201" ref="ul">
          <li v-for="item in loadList" :key="item.place" class="msg">
            <span>{{item.place}}</span>
            <span>{{item.name}}</span>
            <span>{{item.price}}</span>
          </li>
        </ul>
      </div>
    </div>
    <p>查看源码：<a href="https://gitee.com/guozia007/brush-audition/blob/master/src/pages/case-interview/Audition201.vue" target="_blank">虚拟列表实现10万条数据的加载</a></p>
  </div>
</template>

<script>
export default {
  name: 'Audition201',
  data() {
    return {
      listNum: 100000, // 数据总条数
      startIndex: 0, // 可视区第一条的下标
      endIndex: 10, // 可视区最后一条的下标 + 1
      showNum: 10, // 可视区显示的条数
    }
  },
  computed: {
    // 总数据
    list() {
      return new Array(this.listNum).fill({}).map((item, index) => {
        return {
          place: index + 1,
          name: Math.random() > 0.5 ? '蔬菜' : '水果',
          price: (Math.random() * 10).toFixed(2) + '元',
        }
      })
    },
    // 从总的数据中，截取只需要加载到可视区的那10条数据
    loadList() {
      return this.list.slice(this.startIndex, this.endIndex)
    },
  },
  mounted() {
    const cont = this.$refs.content
    const ul = this.$refs.ul
    // 非可视区总高度
    const totalHeight = (this.listNum - this.showNum) * 55
    // 用ul的margin把盒子撑开 定义初始状态
    ul.style.marginTop = 0
    ul.style.marginBottom = totalHeight + 'px'

    cont.addEventListener('scroll', () => {
      let top = cont.scrollTop
      ul.style.marginTop = top + 'px'
      ul.style.marginBottom = totalHeight - top + 'px'
      // 实时更新可视区内容
      this.startIndex = Math.floor(top / 55)
      this.endIndex = Math.ceil(top / 55) + this.showNum
    })
  }
}
</script>

<style lang="less" scoped>
.container {
  width: 624px;
  height: 605px;
  border: 1px solid rgba(193,193,193);
  border-radius: 6px;
  overflow: hidden;

  .msg {
    width: 100%;
    height: 55px;
    line-height: 55px;
    display: flex;
    justify-content: space-around;

    &.msg-head {
      box-shadow: 0px -3px 12px rgb(0 0 0 / 8%);
    }
  }

  .content {
    height: 550px;
    overflow-y: auto;

    // 滚动条整体样式
    &::-webkit-scrollbar {
      width: 5px;
    }
    // 轨道
    &::-webkit-scrollbar-track {
      background-color: transparent;
    }
    // 轨道内滑块
    &::-webkit-scrollbar-thumb {
      background-color: rgba(0 0 0 / 30%);
      border-radius: 2px;
    }
  }
}
</style>